<?php


namespace payment;


use app\service\ImUserService;
use think\facade\Log;

class ImInPay
{

    // 插件配置参数
    private $config;

    /**
     * [__construct 构造方法]
     * @param   [string]     $app_id         [应用appid]
     * @param   [string]     $app_secret     [应用密钥]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-12-30T18:04:05+0800
     */
    public function __construct($params = [])
    {
        $this->config = $params;
    }
    public function upload(array $params = [])
    {
        $a = [
            //"picUrl"                   => "https://shop.dh-w.com/public/image/xieyan/shenfen1.jpg",
            "picName"                   => $params['name']
        ];
        $a['sign'] = self::sign($a);
        $a['picUrl'] = $params['path'];
        $requestUrl = "/api/yoppro/file/upload";
        $jsonStr = json_encode($a,JSON_UNESCAPED_UNICODE);
        $res = self::httpJson($requestUrl, $jsonStr);
       return $res;


    }

    public function inthree($params = [])
    {
        $a1 = [
            "parentMerchantNo"                   => "10034361159",
            "bankCity"                 => "330300", //银行城市编号
            "bankCode"                  => "313333460043", //银行代码
            "bankProvince"              => "330000", //银行省编号
            "cardNo"         => "6224490110090537", //银行卡信息
            "headBankCode"         => "JHYH", //银行代码
            "legalIdCard"         => "330324199601260014", //身份证号
            "legalName"         => "虞文强", //姓名
            "merLegalPhone"         => "13057877872", //银行卡预留手机号
            "mchntType" => "1",
            "merProvince"   => "330000",
            "merCity"       => "330300",
            "merDistrict"   => "330324",
            "merAddress"    => "永嘉县"
        ];

        try {
            $a1['sign'] = self::sign($a1);
            $a1['requestNo'] = 's12348';
            $a1['fileInfo'] = [
                [
                    'quaType' => 'HAND_IDCARD', //个人法人手持身份证
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/26/merchant-1650960619850-6267a8eb3f6b0466821980314c29dcda-SLDYqgPkHLeYWjpudpKp.jpg',
                ],
                [
                    'quaType' => 'IDCARD_FRONT', //法人身份证正面
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/26/merchant-1650960624080-6267a8ee8ebda234414327e9ad40ea5f-QctAPTCfjSJNteFdIexs.jpg',
                ],
                [
                    'quaType' => 'IDCARD_BACK', //法人身份证反面
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/26/merchant-1650960628555-6267a8f30340c589684460aaa6a908a8-ljEOzhBVkACNfKxFakwj.jpg',
                ],
                [
                    'quaType' => 'SETTLE_BANKCARD', //结算银行卡
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/26/merchant-1650960630696-6267a8f5b887f584307884a8782a4bda-jNkSeTcSdJLeoFVydHVZ.jpg',
                ]
            ];
        } catch (\Exception $e) {
            print_r($e->getMessage());
        }
        $requestUrl = "/api/yoppro/merchant/addreq";
        $jsonStr = json_encode($a1, JSON_UNESCAPED_UNICODE);

        $res = self::httpJson($requestUrl, $jsonStr);
        print_r($res);
    }

    public function in($params = [])
    {
        $a1 = [
            "parentMerchantNo"                   => "10034361159",
            "bankCity"                 => "445200",//银行城市编号
            "bankCode"                  => "314587110019",//银行代码
            "bankProvince"              =>"440000",//银行省编号
            "cardNo"         =>"6217281532900339900",//银行卡信息
            "headBankCode"         =>"GDJDRCB",//银行代码
            "legalIdCard"         =>"445221199902056215",//身份证号
            "legalName"         =>"谢志波",//姓名
            "merLegalPhone"         => "17875763481",//银行卡预留手机号
            "mchntType" => "1",
            "merProvince"   => "440000",
            "merCity"       => "445200",
            "merDistrict"   => "445221",
            "merAddress"    => "揭东区"
        ];

        try{
            $a1['sign'] = self::sign($a1);
            $a1['requestNo'] = 's12346';
            $a1['fileInfo'] = [
                [
                    'quaType' => 'IDCARD_FRONT',//法人身份证正面
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/13/merchant-1649850576665-6256b8d0422903471238426ef518b5fc-WLmfugpAdnHmjsWeyLOr.jpg',
                ],
                [
                    'quaType' => 'IDCARD_BACK',//法人身份证反面
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/13/merchant-1649850577918-6256b8d125b5f459501746e53faf5cd7-uyEBeZFqApEnLMCvFEcu.jpg',
                ],
                [
                    'quaType' => 'SETTLE_BANKCARD',//结算银行卡
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/13/merchant-1649850578792-6256b8d26381f7062476120283da56b7-kBQCjamNTkhBfwzRmTuJ.jpg',
                ],
                [
                    'quaType' => 'HAND_IDCARD',//个人法人手持身份证
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/13/merchant-1649850575867-6256b8cf77b7e505175939e9eee949b4-GJIrRXbCqRNtOPDmPDMm.jpg',
                ]
            ];
        }catch(\Exception $e){
            print_r($e->getMessage());

        }
        $requestUrl = "/api/yoppro/merchant/addreq";
        $jsonStr = json_encode($a1,JSON_UNESCAPED_UNICODE);

        $res = self::httpJson($requestUrl, $jsonStr);
        print_r($res);


    }

    public function code()
    {
        $a = [
            "headBankNo"                   => "GDJDRCB",
            "bankProvinceNo"                 => "440000",
            "bankCityNo"          => "445200",
        ];
        $a['sign'] = self::sign($a);
        $requestUrl = "/api/yoppro/bank/branch";
        $jsonStr = json_encode($a,JSON_UNESCAPED_UNICODE);
        $res = self::httpJson($requestUrl, $jsonStr);
        print_r($res);
    }

    public function Pay($params = [])
    {
        //return json(['code' => 0, 'msg' => 'dddd', 'data' => $params]);
        // 参数
        if(empty($params))
        {
            return DataReturn('参数不能为空', -1);
        }

        // 配置信息
        if(empty($this->config))
        {
            return DataReturn('支付缺少配置', -1);
        }
        $a = [
            "account"           => "164931889277666",
            "payMoney"          => $params['total_price'],
            "lowOrderId"        => $params['order_no'],
            "notifyUrl"         => $params['notify_url'],
            "body"              => '商品',
            "returnUrl"         => $params['redirect_url'],
            "payType"           => "1",
            "appId"             => "wx0ca24c69c47958eb",
            "openId"            => $params['user']['weixin_openid'],
            "isMinipg"          => "1",
            "fundProcessType"   => "DELAY_SETTLE"
        ];
        $a['sign'] = self::sign($a);
        $requestUrl = "/tgPosp/services/payApi/wxJspay";
        $jsonStr = json_encode($a,JSON_UNESCAPED_UNICODE);
        $res = self::httpJson($requestUrl, $jsonStr);

        return DataReturn('', 0,$res);
    }

    public static function sign($a)
    {
        $key = 'x023Lh81l9078zuB9M1k1s4iM4Tf67bDdYmHo7x11U2551K9tg76eF0rI0Y4';
        ksort($a);
        $str = '';
        foreach($a as $k => $v){
            $str .= ($k.'='.$v.'&');
        }
        $str = substr($str,0,-1);
        $str .= '&key='.$key;
        $a = strtoupper(md5($str));
        return $a;

    }

    public static function httpJson($url,$jsonStr)
    {
        try{
            // $url = 'https://tgpay.833006.net' .$url;
            $url = 'http://agency.yltg.com.cn' . $url;
           
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length: ' . strlen($jsonStr)
                )
            );
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            return json_decode($response,true);
            return array($httpCode, json_decode($response,true));
        }catch (\Exception $e){

        }
        return [];

    }


    public function Respond($params = [])
    {

        try{
            $result = file_get_contents('php://input');
            Log::record('支付回调数据 '.$result);
            $result = json_decode($result,true);

            $signData = $result;
            unset($signData['sign'],$signData['payoffType'],$signData['settlementChannel']);

            // $syncCharge = ImUserService::charge($result);
            if(isset($result['state']) && $result['state'] == 0 && $result['sign'] === self::sign($signData))
            {

                return DataReturn('支付成功', 0, $this->ReturnData($result));
            }
        }catch(\Exception $e){

            print_r($e->getMessage());

        }
        return DataReturn('处理异常错误', -100);

    }


    private function ReturnData($data)
    {
        // 返回数据固定基础参数
        $data['trade_no']       = $data['upOrderId'];  // 支付平台 - 订单号
        $data['buyer_user']     = $data['openid'];          // 支付平台 - 用户
        $data['out_trade_no']   = $data['lowOrderId'];    // 本系统发起支付的 - 订单号
        $data['subject']        = $data['attach'] ?? '';          // 本系统发起支付的 - 商品名称
        $data['pay_price']      = $data['payMoney'];   // 本系统发起支付的 - 总价
        return $data;
    }


    /**
     * [HttpRequestGet get请求]
     * @param    [string]           $url [url地址]
     * @return   [array]                 [返回数据]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-01-03T19:21:38+0800
     */
    public function HttpRequestGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res, true);
    }

    /**
     * [HttpRequestPost curl模拟post]
     * @param    [string]   $url        [请求地址]
     * @param    [array]    $data       [发送的post数据]
     * @param    [array]    $is_parsing [是否需要解析数据]
     * @return   [array]                [返回的数据]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-09-25T09:10:46+0800
     */
    public function HttpRequestPost($url, $data, $is_parsing = true)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_POST, true);

        $res = curl_exec($curl);
        if ($is_parsing === true) {
            return json_decode($res, true);
        }
        return $res;
    }

}
